<?php
namespace app\home\controller;

use think\facade\Db;
use think\facade\Log;
use app\home\BaseController;
class Translation
{
    // 百度翻译API配置
    private $appId = '20250630002393440';
    private $appKey = 'zMuniJSMIVoBRlApdHox';

    /**
     * 执行批量翻译
     */
    public function run()
    {
        // 设置最大执行时间（0为无限制）
        set_time_limit(0);

        // 脚本参数
        $batchSize = 10;      // 每次处理数量
        $delaySeconds = 5;    // 批处理间隔秒数
        $maxRetries = 3;      // 最大重试次数

        // 获取待翻译总数
        $totalItems = Db::name('goods')
            ->whereRaw('tips is not null and content is not null')
            ->where('is_mail', 1)
            ->count();
        if ($totalItems === 0  ) {
            Log::info("没有待翻译的商品");
            exit;
        }

        Log::info("开始翻译任务，待处理商品: {$totalItems} 条\n", []);
        // 计算批次数
        $batchCount = ceil($totalItems / $batchSize);
        $processedItems = 0;
        $successCount = 0;

        for ($i = 0; $i < $batchCount; $i++) {
            // 获取一批待翻译商品
            $batch = Db::name('goods')
                ->field('id,spu_id,content,tips,sku_key,sku_value,sku_key2,sku_value2,sku_key3,sku_value3')
                ->whereRaw('tips is not null and content is not null')
                ->where('is_mail', 1)
                ->limit($batchSize)
                ->select()
                ->toArray();
            if (empty($batch)) {
                Log::info("没有更多待处理商品");
                break;
            }

            // 准备翻译文本
            $texts = [];

            foreach ($batch as $key=>$item) {
                $array = array_filter(json_decode($item['content']), function($value) {
                    return !empty($value);
                });
                $batch[$key]['temp'] = $array;
                $texts = array_merge($texts,$array);
            }
            // 调用翻译API
            $translations = $this->baiduTranslate($texts);
            // 处理并保存结果
            $batchSuccess = $this->saveResults($batch, $translations);
            $successCount += $batchSuccess;

            $processedItems += count($batch);
            $progress = round(($processedItems / $totalItems) * 100, 2);

            //echo "进度: {$progress}% ({$processedItems}/{$totalItems}) | 本批成功: {$batchSuccess}/".count($batch)."\n";

            // 非最后一批时等待
            if ($i < $batchCount - 1) {
                sleep($delaySeconds);
            }
        }
        Log::info("翻译任务完成! 成功: {$successCount}, 失败: " . ($processedItems - $successCount),[]);
    }

    /**
     * 调用百度翻译API
     */
    private function baiduTranslate(array $texts)
    {
        $salt = time() . mt_rand(1000, 9999);
        $signStr = $this->appId . implode("\n", $texts) . $salt . $this->appKey;

        $sign = md5($signStr);

        $postData = [
            'q' => implode("\n", $texts),  // 关键修正：使用换行符连接文本
            'from' => 'jp',
            'to' => 'zh',
            'appid' => $this->appId,
            'salt' => $salt,
            'sign' => $sign
        ];
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => 'https://fanyi-api.baidu.com/api/trans/vip/translate',
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => http_build_query($postData),
            CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
            CURLOPT_TIMEOUT => 15,
            CURLOPT_CONNECTTIMEOUT => 5
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($httpCode !== 200) {
            $error = curl_error($ch);
            curl_close($ch);
            throw new \Exception("API请求失败: HTTP {$httpCode} - {$error}");
        }

        curl_close($ch);

        // 解析响应
        $data = json_decode($response, true);

        if (!isset($data['trans_result'])) {
            $errorCode = $data['error_code'] ?? 'unknown';
            $errorMsg = $data['error_msg'] ?? 'No error message';
            throw new \Exception("翻译错误: [{$errorCode}] {$errorMsg}");
        }

        // 构建翻译结果映射
        $resultMap = [];
        foreach ($data['trans_result'] as $item) {
            $resultMap[$item['src']] = $item['dst'];
        }

        return $resultMap;
    }

    /**
     * 保存翻译结果
     */
    private function saveResults(array $batch, array $translations)
    {
        $successCount = 0;

        Db::startTrans();
        try {
            foreach ($batch as $item) {
                $tips = explode('|',$item['tips']);
                $updateData = [
                    'sku_key' => !empty($tips[0]) ?  $tips[0] : '',
                    'sku_key2' => !empty($tips[1]) ?  $tips[1] : '',
                    'sku_key3' => !empty($tips[2]) ?  $tips[2] : '',
                    'sku_value' => !empty($item['temp'][0]) && !empty($translations[$item['temp'][0]]) ? $translations[$item['temp'][0]] :  null,
                    'sku_value2' => !empty($item['temp'][1]) && !empty($translations[$item['temp'][1]]) ? $translations[$item['temp'][1]] :  null,
                    'sku_value3' => !empty($item['temp'][2]) && !empty($translations[$item['temp'][2]]) ? $translations[$item['temp'][2]] :  null,
                    'is_mail' => 0,
                    'update_time' => date('Y-m-d H:i:s')
                ];
                $result = Db::name('goods')
                    ->where('id', $item['id'])
                    ->update($updateData);

                if ($result) {
                    $successCount++;
                }
            }

            Db::commit();
            return $successCount;
        } catch (\Exception $e) {
            Db::rollback();
            echo "保存失败: " . $e->getMessage() . "\n";
            return 0;
        }
    }
}